package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.AddressBootDTO;
import com.sky.entity.AddressBootEntity;
import com.sky.mapper.AddressBootMapper;
import com.sky.service.AddressBootService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AddressBootServiceImpl implements AddressBootService {

    @Autowired
    private AddressBootMapper addressBootMapper;

    @Override
    public void add(AddressBootDTO dto) {
        AddressBootEntity entity = new AddressBootEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setUserId(BaseContext.getId());
        log.info("entity =>{}", entity);
        addressBootMapper.add(entity);
    }

    @Override
    public List<AddressBootEntity> list() {
        List<AddressBootEntity> list = addressBootMapper.getByUserId(BaseContext.getId());
        return list;
    }

    @Override
    public AddressBootEntity getDefault() {
        AddressBootEntity entity = addressBootMapper.getDefault(BaseContext.getId());
        return entity;
    }

    @Override
    public void update(AddressBootDTO dto) {
        AddressBootEntity entity = new AddressBootEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setUserId(BaseContext.getId());
        addressBootMapper.update(entity);
    }

    @Override
    public void delete(Long id) {
        addressBootMapper.delete(id);
    }

    @Override
    public AddressBootEntity getById(Long id) {
        return addressBootMapper.getById(id);
    }

    @Override
    @Transactional
    public void setDefault(AddressBootDTO dto) {
        /**
         * 1. 将当前用户地址设置为默认
         * 2. 将当前用户其他地址设置为非默认
         */
        Long userId = BaseContext.getId();
        List<AddressBootEntity> list = addressBootMapper.getByUserId(userId);

        List<Long> ids = list.stream().map(AddressBootEntity::getId).collect(Collectors.toList());
        log.info("将所有地址设置为非默认 =>{}", ids);
        addressBootMapper.cleanDefault(ids);
        AddressBootEntity entity = AddressBootEntity.builder().id(dto.getId()).userId(userId).isDefault(0).build();

        addressBootMapper.update(entity);
    }
}
